﻿using Aliyun.OSS;
using Aliyun.OSS.Common;
using CommonLibrary.Helper;
using DataModel.Contants;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CommonLibrary.Pools
{
    public class PictureDownloadPool
    {
        public class PictureDownloadTask : ITask
        {
            private readonly string _url;
            private readonly object locker = new();

            public PictureDownloadTask(string url)
            {
                _url = url;
            }

            public void Execute()
            {
                var data = OssHelper.GetObject(AppDefines.OssConfig, _url);
                if (data == null)
                {
                    return;
                }

                string cachePath = DomainHelper.GetCachedFilePath(_url);
                lock (locker)
                {
                    File.WriteAllBytes(cachePath, data);
                }

                Thread.Sleep(100);
            }
        }

        public static void Downloads(string[] urls, Action<BatchResult> callback)
        {
            var batchTasks = new List<ITask>();
            foreach (var url in urls)
            {
                batchTasks.Add(new PictureDownloadTask(url));
            }

            ThreadPoolFactory.AdvancedPoolHandler.EnqueueBatch(batchTasks, callback);
        }

        public static void Download(string url, Action<BatchResult> callback)
        {
            var batchTasks = new List<ITask>(1);
            batchTasks.Add(new PictureDownloadTask(url));
            ThreadPoolFactory.AdvancedPoolHandler.EnqueueBatch(batchTasks, callback);
        }
    }
}
